package cn.zaink;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.nio.charset.StandardCharsets;

/**
 * 简单写
 *
 * @author zenghy
 **/
@Slf4j
public class SimpleWriteTest extends AbstractZkClient {

    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        String counter = context.getParameter(Arg.COUNTER);
        String prefix = context.getParameter(Arg.NODE_PREFIX);
        int wCounter = context.getIntParameter(Arg.W_COUNTER);
        log.warn("ZK第{}写", wCounter);

        SampleResult result = new SampleResult();
        result.setSampleLabel("ZK节点写测试");
        try {
            // 开始样品事物
            result.sampleStart();
            result.setTimeStamp(System.currentTimeMillis());
            String path = prefix.concat("/node") + counter;
            int counterInt = Integer.parseInt(counter);
            if (counterInt > 1024) {
                // zk节点数过多会导致异常
                path = prefix.concat("/node") + RandomUtil.randomInt(0, 1024) + "/node" + counter;
            }
            client.create().forPath(path, String.valueOf(System.currentTimeMillis()).getBytes());
            result.setSuccessful(true);
        } catch (Exception e) {
            log.error("创建zk节点出错：".concat(e.getMessage()));
            result.setSuccessful(false);
            result.setResponseData(e.getMessage(), StandardCharsets.UTF_8.name());
        } finally {
            result.sampleEnd();
            result.setEndTime(System.currentTimeMillis());
            result.setDataType(SampleResult.TEXT);
            latch.countDown();
        }
        return result;
    }
}
